package com.elitetyc.eliteim.client.service;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.elitetyc.eliteim.client.EliteIMClient;
import com.elitetyc.eliteim.client.config.IMClientProperties;
import com.elitetyc.eliteim.client.thread.ReConnectJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * @author yuanchao.tan
 * @version 1.0
 * @description 重连服务
 * @Date 2021/9/17 12:27
 */
@Service
@Slf4j
public class ReConnectService {

    private ScheduledExecutorService scheduledExecutorService;

    @Autowired
    private EliteIMClient eliteIMClient;

    @Autowired
    private IMClientProperties imClientProperties;

    /**
     * 开始重连
     */
    public void reConnect(){
        if (scheduledExecutorService==null||scheduledExecutorService.isShutdown()){
            final ThreadFactory threadFactory = new ThreadFactoryBuilder()
                    .setNamePrefix("reConnect-job-")
                    .build();
            scheduledExecutorService =  new ScheduledThreadPoolExecutor(1,threadFactory);
        }
        scheduledExecutorService.scheduleAtFixedRate(new ReConnectJob(eliteIMClient,scheduledExecutorService,imClientProperties)
                ,0,10, TimeUnit.SECONDS);
    }
}
